<?php

/**
* 
*/
class AbstractConfigurator
{
	
	/**
	 * Configurator resources
	 *
	 * @var Array
	 */
	protected $_resources;
	
	protected $_rootDirectory;
	public function getRootDirectory(){
		return $this->_rootDirectory;
	}
	public function setRootDirectory($rootDirectory){
		if(!is_dir($rootDirectory)){
			throw new Exception("Bad directory ".$rootDirectory);
		}
		
		$this->_rootDirectory = $rootDirectory;
	}
	
	protected $_environment;
	public function getEnvironment(){
		return $this->_environment;
	}
	public function setEnvironment($environment){
		$this->_environment = $environment;
		return $this;
	}
	
	protected $_applicationPath = 'app';
	
	public function __construct(){
		$this->_init();
		$this->setup();
	}
	
	//-----------------------------
	//
	// Public functions
	//
	//-----------------------------
	public function bootstrap($env = 'dev'){
		$this->setEnvironment($env);
		
		ClassLoader::getInstance()->addClassPath(realpath($this->_rootDirectory.'/'.$this->_applicationPath));
		
		foreach ($this->_resources as $resource) {
			$options = $this->_getOptionsForResouce($resource);
			$resource->setOptions($options)->init();
		}
		
		return $this;
	}
	
	public function run(){
		
		foreach ($this->_resources as $resource) {
			$resource->run();
		}
		
		return $this;		
	}
	
	public function setup(){}
	
	public function registerResource(AbstractConfiguratorResource $resource){
		$resource->setConfigurator($this);
		$this->_resources[] = $resource;
 	}
 	
	protected function _init(){
		$this->_resources = array();
	}
	
	protected function _getOptionsForResouce(AbstractConfiguratorResource $resource){
		$class = get_class($resource);
		
		$configFile = $this->_rootDirectory.'/config/'. str_replace('resource','',strtolower(get_class($resource))) . '.json';
		
		if(!file_exists($configFile)){
			return array();
		}
		
		import('miho.config.Config');
		$options = Config::getInstance()->getFromFile($configFile)->getValues();
		
		return $options;
	}
		
}


?>